﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace iFinity.DNN.Modules.NewsArticlesSiteMapProvider
{
    /// <summary>
    /// Methods adapted from the News Articles codebase to provide similar conversion of the title.
    /// This method may fall out of synchronisation with the in-built code in the Ventrian News Articles.
    /// If so, modifications will need to be made to this code to bring it back into line with the News Articles Urls
    /// </summary>
    class UrlUtilities
    {

        public static string FormatTitle(string title, string replaceChar)
        {
            string result = title;
            if (string.IsNullOrEmpty(title))
            {
                result = DotNetNuke.Common.Globals.glbDefaultPage;
            }
            else
            {
                result = OnlyAlphaNumericChars(title, replaceChar);
                if (string.IsNullOrEmpty(result))
                {
                    return DotNetNuke.Common.Globals.glbDefaultPage;
                }
            }
            result = result.Replace("--", "-") + ".aspx";
            return result;
        }
        public static string OnlyAlphaNumericChars(string original, string replaceChar)
        {
            string result = "";
            string sChar = null;

            original = RemoveDiacritics(original.Trim());
            foreach (char c in original.ToCharArray())
            {
                sChar = c.ToString();
                if (IsAlphaNumeric(sChar) || sChar == "-" || sChar == "_")
                {
                    result += sChar;
                }
                else
                    if (sChar == " ")
                        result += replaceChar;
            }
            return result;

        }

        public static string RemoveDiacritics(string input)
        {
            input = input.Normalize(System.Text.NormalizationForm.FormD);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (char c in input)
            {
                if (c.ToString() == char.ConvertFromUtf32(305))
                    sb.Append('i');
                else
                    if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
                    {
                        sb.Append(c);
                    }
            }
            return sb.ToString();
        }

        public static bool IsAlphaNumeric(string value)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(value, @"[0-9A-Za-z]", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.CultureInvariant);   
        }

    }
}
